package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.handle.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 客户端
 */
public class RpcClient {

    //1.连接Netty服务端
    //2.提供给调用者主动关闭资源的方法
    //3.提供消息发送的方法

    private Channel channel;
    private EventLoopGroup group;
    private String ip;

    private int port;

    /**
     * 客户端处理类
     */
    private RpcClientHandler rpcClientHandler = new RpcClientHandler();

    /**
     * 线程池
     */
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public RpcClient(String ip, int port){
        this.ip = ip;
        this.port = port;
        initClient();
    }

    /**
     * 初始化
     */
    public void initClient(){

        try {
            //1/创建线程组
            group = new NioEventLoopGroup();

            //2.创建启动助手
            Bootstrap bootstrap = new Bootstrap();

            //3.设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)//设置活跃状态
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)//设置超时时间
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();

                            //String 类型编解码器
                            channelPipeline.addLast(new StringDecoder());
                            channelPipeline.addLast(new StringEncoder());

                            channelPipeline.addLast(rpcClientHandler);
                        }
                    });

            channel = bootstrap.connect(ip, port).sync().channel();
        }catch (Exception e){
            e.printStackTrace();
            if(channel != null){
                channel.close();
            }

            if(group != null){
                group.shutdownGracefully();
            }
        }

    }

    /**
     * 提供调用者主动关闭资源的方法
     */
    public void close(){
        if(channel != null){
            channel.close();
        }

        if(group != null){
            group.shutdownGracefully();
        }
    }


    /**
     * 提供消息发送的方法
     * @param msg
     * @return
     */
    public Object send(String msg) throws Exception{
        rpcClientHandler.setRequestMsg(msg);
        Future submit = executorService.submit(rpcClientHandler);
        Object o = submit.get();
        return o;
    }
}
